package com.caisejingyu.whales.home.ui

import android.Manifest
import android.arch.lifecycle.Observer
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v7.widget.LinearLayoutManager
import android.view.SurfaceHolder
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.caisejingyu.whales.common.L
import com.caisejingyu.whales.common.ui.SimpleActivity
import com.caisejingyu.whales.common.utils.FileUtil
import com.caisejingyu.whales.common.utils.FileUtil.SAVE_PIC_PATH
import com.caisejingyu.whales.common.utils.FileUtil.WHALES_PATH
import com.caisejingyu.whales.common.utils.LaunchHelper
import com.caisejingyu.whales.common.utils.SPUtil
import com.caisejingyu.whales.home.adapter.PhotoFrameAdapter
import com.caisejingyu.whales.home.common.BitmapUtil
import com.caisejingyu.whales.home.common.Defines
import com.caisejingyu.whales.home.common.UiTask
import com.caisejingyu.whales.home.data.BannerRespons
import com.caisejingyu.whales.home.devices.camera.CameraListener
import com.caisejingyu.whales.home.devices.camera.CameraServiceImpl
import com.caisejingyu.whales.home.devices.camera.ICameraManage
import com.caisejingyu.whales.home.devices.printer.PrintFaceFactory
import com.caisejingyu.whales.home.devices.printer.PrintPageConstants
import com.caisejingyu.whales.home.devices.printer.PrintServiceFactory
import com.caisejingyu.whales.home.vm.HomePresenter
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.home_error_layout.*
import kotlinx.android.synthetic.main.home_hint_layout.*
import kotlinx.android.synthetic.main.home_interval_layout.*
import kotlinx.android.synthetic.main.home_photo_frame_layout.*
import kotlinx.android.synthetic.main.home_printing_view.*
import kotlinx.android.synthetic.main.home_taking_layout.*
import kotlinx.android.synthetic.main.home_top_layout.*
import com.caisejingyu.whales.home.R
import com.caisejingyu.whales.home.common.Defines.DEFALULT_PICTURE_POSITION
import com.caisejingyu.whales.home.common.Defines.TAG
import com.caisejingyu.whales.home.data.InitResponst
import com.caisejingyu.whales.home.devices.camera.CameraInterface
import com.caisejingyu.whales.home.devices.printer.PrinterService
import java.net.UnknownHostException
import kotlin.concurrent.thread


class HomeActivity : SimpleActivity(), PhotoFrameAdapter.ItemOnClickListener {
//    private lateinit var cameraManage: ICameraManage
    private val requestCode = 99
    private val presenter = HomePresenter(this)
    private val activity = this
    private var countDownTimer: CountDownTimer? = null
    private val photoFrameAdapter = PhotoFrameAdapter(presenter.photoFrameData, this)
    private var path = ""

    private val previewRate = -1f


    override fun init(savedInstanceState: Bundle?) {
        // 申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA), 2)
        }
        // 打印机初始化
        PrintServiceFactory.INSTANCE().cancelPrinte()
        // 相机初始化
//        cameraManage = CameraServiceImpl().cameraManage(this, surfaceView)
        scrollerViewpager?.isClickable = false
        initView(Defines.HOME_VIEW_STATUS_INIT)
        printingParent.visibility = View.GONE           //打印中 父view
        setListener()
        setPhotoFrame()
        presenter.pollingPrint()
        presenter.pollingCmd()
        presenter.initRahmen()
        presenter.initScrollView()
        presenter.machineInit()

        //测试
        test()
    }

    override fun onResume() {
        super.onResume()
        Thread {
            kotlin.run {
                CameraInterface.getInstance().doOpenCamera {
                    Thread.sleep(1000)
                    val holder = surfaceView.surfaceHolder
                    CameraInterface.getInstance().doStartPreview(holder, previewRate);
                }
            }
        }.start()
    }


    override fun layoutId(): Int {
        return R.layout.activity_home
    }

    private fun initView(status: Int) {
        when (status) {
            Defines.HOME_VIEW_STATUS_INIT -> {
                takingPictures.visibility = View.VISIBLE        //拍照
                photoFrameParent.visibility = View.VISIBLE      //选择相框 父view
                topViewParent.visibility = View.VISIBLE         //顶部 父view
                intervalParentView.visibility = View.GONE       //倒计时 父view
                takingHintParent.visibility = View.GONE         //提示 父view
                errorParentView.visibility = View.GONE          //错误的 父view
            }
            Defines.HOME_VIEW_STATUS_TAKING_PICTURE -> {
                intervalParentView.visibility = View.VISIBLE
                takingPictures.visibility = View.GONE
                photo.visibility = View.GONE
                photoFrameParent.visibility = View.GONE
                topViewParent.visibility = View.GONE
            }
            Defines.HOME_VIEW_STATUS_PRINTING -> {
            }
        }
    }

    //测试
    private fun test() {
        //打开打印页面
        phone.setOnClickListener {
            LaunchHelper.getInstance().launch(this, PhotoPaymentActivity::class.java)
        }

        //打开摄像头测试页面
        camera.setOnClickListener {
            LaunchHelper.getInstance().launch(this, CameraTestActivity::class.java)
        }

        //网络的测试
        network.setOnClickListener {
        }

        //测试打印
        btn_print.setOnClickListener {
            PrintServiceFactory.INSTANCE().print("/mnt/internal_sd/whales/ar/photos/demo.jpg",
                    null, null, PrintFaceFactory.getPrinterFace(PrintPageConstants.getPrintPageType()))
        }

        //图片合成
        btn_combine.setOnClickListener {
            LaunchHelper.getInstance().launch(this, CombineTestActivity::class.java)
        }

        shopPolling.setOnClickListener {
            presenter.cancelPollingPrint()
        }

    }

    private fun setListener() {
        //点击拍照
        takingPictures.setOnClickListener {
            initView(Defines.HOME_VIEW_STATUS_TAKING_PICTURE)
            interval()
        }

        //拍照的回调
        CameraInterface.getInstance().setCameraListener(object : CameraListener {
            override fun cameraCallback(bitmap: Bitmap) {
                photo.visibility = View.VISIBLE
                intervalText.visibility = View.GONE
                var comPoundBitmap: Bitmap? = null
                if (photoFrame.visibility == View.VISIBLE) {
                    comPoundBitmap = BitmapUtil.toConformBitmap(bitmap, BitmapUtil.drawableToBitmap(photoFrame.drawable))
                }
                if (comPoundBitmap != null) {
                    photo.setImageBitmap(comPoundBitmap)
                } else {
                    comPoundBitmap = bitmap
                }

                path = "${System.currentTimeMillis()}photo.jpg"
                FileUtil.saveFile(comPoundBitmap, path, FileUtil.WHALES_PATH)
                //跳转的支付页面
                UiTask.handler.postDelayed({
                    val intent = Intent(activity, PhotoPaymentActivity::class.java)
                    intent.putExtra("path", SAVE_PIC_PATH + WHALES_PATH + "/" + path)
                    startActivityForResult(intent, requestCode)
                }, 500)
            }
        })

        //异常的上报
        topViewParent.setOnClickListener {
            SPUtil.getString(Defines.PHONE_QR_CODE)?.let {
                presenter.showQRCodeDialog(supportFragmentManager, it)
            }
        }

        //打印手中的照片
        printPhonePicture.setOnClickListener {
            SPUtil.getString(Defines.PUBLIC_QR_CODE)?.let {
                presenter.showQRCodeDialog(supportFragmentManager, it)
            }
        }

        //网络异常的回调
        presenter.errorException.observe(this, Observer {
            if (it != null && it is UnknownHostException) {
                errorParentView.visibility = View.VISIBLE
                printTopParent.visibility = View.GONE
            } else {
                errorParentView.visibility = View.GONE
                printTopParent.visibility = View.VISIBLE
            }
        })

        // 相框回调
        presenter.liveDataRefreshLiveData.observe(this, Observer<Void> {
            photoFrameAdapter.notifyDataSetChanged()
            if (presenter.photoFrameData.size > 0) {
                presenter.photoFrameData[DEFALULT_PICTURE_POSITION].isSelect = true
                itemOnClick(DEFALULT_PICTURE_POSITION)
            }
        })

        //获取轮播图
        presenter.liveDataInitScrollerViewpagerLiveData.observe(this, Observer<List<BannerRespons>> {
            it?.let {
                val imgs = ArrayList<View>()
                for (banner in it) {
                    imgs.add(ImageView(this).apply {
                        Glide.with(this@HomeActivity).load(banner.image).into(this)
                        this.scaleType = ImageView.ScaleType.FIT_XY
                    })
                }
                scrollerViewpager?.init(imgs, 2)
            }
        })

        //机器的初始化
        presenter.liveDataInitMachineLiveData.observe(this, Observer<InitResponst> {
            it?.let {
                devicesCode.text = ("机器码：${it.machineCode}")
                serviceTelephone.text = ("客服电话：${it.servicePhone}")
            }
        })

        presenter.printStatusLiveData.observe(this, Observer { data ->
            data?.let {
                if ((it.count == null || it.count == 0) && it.status == Defines.PRINT_STATUS_START) {
                    L.f().e(TAG, "打印状态回调--没有数量")
                    printingParent.visibility = View.GONE
                    return@Observer
                } else {
                    L.f().e(TAG, "打印状态回调--张数 = ${it.count} ， 状态 = ${if (data.status == Defines.PRINT_STATUS_START) "开始" else "结束"}")
                    printingParent.visibility = View.VISIBLE
                    printCount.text = it.count.toString()
                    if (it.status == Defines.PRINT_STATUS_START) {
                        imageViewProcess.start(60000, 0, 100)
                    } else {
                        imageViewProcess.start(1000, /**/80, 100)
                    }
                    if (it.status == Defines.PRINT_STATUS_END) {
                        imageViewProcess.postDelayed({
                            L.f().e(TAG, "打印状态回调--关闭打印中")
                            printingParent.visibility = View.GONE
                        }, 2000)
                    }
                }
            }
            if (data == null) {
                L.f().e(TAG, "打印状态回调--数据异常")
            }

        })
    }

    /**
     * 倒计时，拍照
     */
    private fun interval() {
        countDownTimer = object : CountDownTimer(4000, 500) {
            override fun onTick(millisUntilFinished: Long) {
                val intervalTime = millisUntilFinished / 1000
                intervalText.visibility = View.VISIBLE
                intervalText.text = intervalTime.toString()
            }

            override fun onFinish() {
                intervalText.text = "0"
                //拍照
                CameraInterface.getInstance().doTakePicture()
                countDownTimer?.cancel()
            }
        }
        countDownTimer?.start()
    }

    /**
     * 设置相框
     */
    private fun setPhotoFrame() {
        recyclerView.adapter = photoFrameAdapter
        recyclerView.layoutManager = LinearLayoutManager(activity)
        photoFrameAdapter.notifyDataSetChanged()
        //相框的显示与隐藏
        switchPhotoFrame.setOnClickListener {
            val isVisibility = recyclerView.visibility == View.VISIBLE
            if (isVisibility) {
                recyclerView.visibility = View.GONE
                switchPhotoFrameText.visibility = View.VISIBLE
            } else {
                recyclerView.visibility = View.VISIBLE
                switchPhotoFrameText.visibility = View.GONE
            }
        }
    }

    //点击选择相框
    override fun itemOnClick(position: Int) {
        if (position == 0) {
            photoFrame.visibility = View.GONE
        } else {
            photoFrame.visibility = View.VISIBLE
            Glide.with(activity).load(presenter.photoFrameData[position].url).into(photoFrame)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        initView(Defines.HOME_VIEW_STATUS_INIT)
    }


    override fun onStart() {
        super.onStart()
//        cameraManage.restart()
    }

    override fun onPause() {
        super.onPause()
        CameraInterface.getInstance().doStopCamera();
    }

    override fun onDestroy() {
        super.onDestroy()
        presenter.onDestroy()
    }
}